package zinx

import (
	"awesomeProject/zinx/utils"
	"awesomeProject/zinx/ziface"
	"fmt"
	"strconv"
)

type MsgHandler struct {
	Apis map[uint32] ziface.IRouter
	WorkerPoolSize uint32
	TaskQueue []chan ziface.IRequest
}

func NewMsgHandle()*MsgHandler  {
	return &MsgHandler{
		Apis: make(map[uint32]ziface.IRouter),
		WorkerPoolSize: utils.GlobalObject.WorkerPoolSize,
		TaskQueue: make([]chan ziface.IRequest,utils.GlobalObject.WorkerPoolSize),
	}
}

func (mh *MsgHandler ) DoMsgHandler(request ziface.IRequest)  {
	handle,ok := mh.Apis[request.GetMsgID()]
	if !ok  {
		fmt.Println("api msgID=",request.GetMsgID(),"Is Not Found!")
		return
	}
	handle.PreHandle(request)
	handle.Handle(request)
	handle.PostHandle(request)
}

func (mh *MsgHandler )AddRouter(msgID uint32,router ziface.IRouter){
	if _,ok :=mh.Apis[msgID];ok {
		panic("repeat api,msgID="+strconv.Itoa(int(msgID)))
	}
	mh.Apis[msgID] = router
}

//启动一个工作池
func (mh *MsgHandler) StartWorkerPool()  {
	for i:=0;i<int(mh.WorkerPoolSize);i++ {
		mh.TaskQueue[i] = make(chan ziface.IRequest,utils.GlobalObject.MaxWorkerTaskLen)
		go mh.startOneWorker(i,mh.TaskQueue[i])
	}
}

func (mh *MsgHandler) startOneWorker(workerId int,taskQueue chan ziface.IRequest)  {
	fmt.Println("startOneWorker workId:",workerId)
	for  {
		select {
		case request:= <- taskQueue:
			mh.DoMsgHandler(request)
		}
	}
}

//将消息交给TaskQueue，由worker进行处理
func (mh *MsgHandler) SendMsgToTaskQueue(request ziface.IRequest)  {
	workerId := request.GetConnection().GetConnId() % mh.WorkerPoolSize
	mh.TaskQueue[workerId] <- request
}
